import datetime
from flask_login import UserMixin
from exts import db,loginmanager

@loginmanager.user_loader
def load_user(id):
    return User.query.get(id) 

# 多对多(many-to-many)关系
# 如果您想要用多对多关系，您需要定义一个用于关系的辅助表。对于这个辅助表， 强烈建议不使用模型，而是采用一个实际的表
followers = db.Table('followers',
    db.Column('follower_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('followed_id', db.Integer, db.ForeignKey('user.id'))
)

class User(db.Model,UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50),unique=True,nullable=False)
    password = db.Column(db.String(80),nullable=False)
    email= db.Column(db.String(100),unique=True,nullable=False)
    timestamp=db.Column(db.DateTime,default=datetime.datetime.now())    
    avatar_img=db.Column(db.String(200),default='/static/default.jpg',nullable=False)
    posts = db.relationship('Post', backref=db.backref('author',lazy=True)) #一对多(one-to-many)关系
    followed = db.relationship(
        "User",secondary=followers,
        primaryjoin=(followers.c.follower_id ==id),
        secondaryjoin=(followers.c.followed_id ==id),
        backref=db.backref('followers',lazy=True),lazy=True)
    
    def is_following(self,user):
        return self.followed.count(user)>0
    
    def follow(self,user):
        if not self.is_following(user):
            self.followed.append(user)

    def unfollow(self,user):
        if  self.is_following(user):
            self.followed.remove(user)   


        
    
    def __repr__(self):
        return '<User %r>' % self.username
    def to_dict(self):
        return {
            'id':self.id,
            'username':self.username,
            'passowrd':self.password,
            'timetamp':self.timetamp.strftime("%Y-%m-%d %H:%M:%S")
        }

class Post(db.Model):
    id=db.Column(db.Integer,primary_key=True)
    body=db.Column(db.String(200),nullable=False)
    timestamp=db.Column(db.DateTime,default=datetime.datetime.now())
    user_id=db.Column(db.Integer, db.ForeignKey('user.id'),nullable=False) #一对多(one-to-many)关系

    def __repr__(self):
        return f'body:{self.body}'
